package cn.minhx.domain.strategy.service.rule.tree.impl;

import cn.minhx.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.minhx.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cn.minhx.domain.strategy.repository.IStrategyRepository;
import cn.minhx.domain.strategy.service.armory.IStrategyDispatch;
import cn.minhx.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.minhx.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 库存扣减节点
 *
 * @author min
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Long awardId, String ruleValue) {
        log.info("决策树引擎【库存扣减节点】开始 userId={} strategyId={} awardId={}  ruleValue={}", userId, strategyId, awardId, ruleValue);

        // 尝试扣减库存
        Boolean flag = strategyDispatch.subtractAwardStock(strategyId, awardId);

        if (flag) {
            // 库存扣减成功，接管，返回奖品ID，奖品规则配置
            log.info("决策树引擎【库存扣减节点】库存扣减成功 userId={} strategyId={} awardId={} ruleValue={}", userId, strategyId, awardId, ruleValue);

            // 写入延迟队列，延迟消费更新数据库记录【trigger中的job[UpdateAwardStockKeyJob]进行消费】
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                            .strategyId(strategyId).awardId(awardId).build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        // 库存扣减失败，放行
        log.warn("决策树引擎【库存扣减节点】库存不足 userId={} strategyId={} awardId={} ruleValue={}", userId, strategyId, awardId, ruleValue);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }

}
